/*
 * @Author: owen 
 * @Date: 2017-11-28 14:45:07 
 * @Last Modified by: owen
 * @Last Modified time: 2017-11-30 15:58:45
 * 数据库管理模块
 */

package models

import (	
	"github.com/owen/olog"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"	// 使用beego orm的时候要先导入mysql驱动

)

const this_file string = "oneNetDao.go"

type User struct {
	Id int `json:"id"`
	Name string `json:"name"`
	Username string `json:"username"`
	Password string `json:"password"`
}

type UserDeviceList struct{
	Id int `json:"id"`
	Username string `json:"username"`	
	DeviceID int	`json:"device_id"`
	Nickname string `json:"nickname"`
}

type DeviceData struct {
	Id int `json:"id"`
	DeviceID int	`json:"device_id"`
	DeviceMsg string `json:"device_msg"`
}


const BD_USING string = "default"
var OneOrm orm.Ormer

type DBStruct struct{
	DbOrm string
	DbDrive string
	DbUser string
	DbPassword string
	DbUrl string
	DbName string
} 

/**
 * 数据库结构初始化
 * 数据库建立链接  
 */
func MysqlInit() bool{

	orm.RegisterModel(new(User),new(UserDeviceList),new(DeviceData))

	dbunit := DBStruct{}
	dbunit.DbOrm = BD_USING
	dbunit.DbDrive = "mysql"
	dbunit.DbUser = "root"
	dbunit.DbPassword = "111111"
	dbunit.DbUrl = "tcp(120.55.58.176:3306)"
	dbunit.DbName = "godb"

	dbSource := dbunit.DbUser+":"+dbunit.DbPassword+"@"+dbunit.DbUrl+"/"+dbunit.DbName+"?"+"charset=utf8"
	var err error
	err = orm.RegisterDataBase(BD_USING, dbunit.DbDrive, dbSource)
	if err != nil {
		olog.Debug(this_file,"db connect fail")
		return false
	}else{
		olog.Debug(this_file,dbSource)
		
	}
	err = orm.RunSyncdb(BD_USING, false, true)	// true 改成false，如果表存在则会给出提示，如果改成false则不会提示 ， 这句话没有会报主键不存在的错误
	if err != nil {
		olog.Debug(this_file,"db run sync fail")
		return false
	}
	OneOrm = orm.NewOrm()
	OneOrm.Using(BD_USING)
	return true
}

/**
 *检验用户登录是否存在 
 */
func CheckUserLogin(username string,password string) bool {
	user:=User{}
	user.Username = username
	err:=OneOrm.Read(&user, "username")
	if err!= nil{
		olog.Debug(this_file,"could't find user:",username)
	}else{
		if user.Password != password {
			return false
		}
		olog.Debug(this_file,"find user:",username)
		return true
	}
	return false
}

/*
*检验用户注册
*/
func CheckUserRegiset(username string,password string) bool{
	user:=User{}
	user.Username = username
	err:=OneOrm.Read(&user, "username")
	if err!= nil{
		user.Username = username
		user.Password = password
		OneOrm.Insert(&user)
		return true	
	}else{
		return false
	}
}

/**
 * 插入设备数据
 * 
*/
func InsertDeviceMsg(deviceID int,msg string){
	data:=DeviceData{}
	data.DeviceID = deviceID
	data.DeviceMsg = msg
	OneOrm.Insert(&data)
}
